using System;
using System.Collections;
using System.Net.Mail;
using System.Net;

namespace TrackingAssist
{
    public class SendMail
    {
        private MailMessage mail;
        private String smtpServer;

        private String sendTo;
        private String sendCC;
        private String sentFrom;
        private String subject;
        private String body;

        /// <summary>
        /// Constructor to send mail
        /// </summary>
        public SendMail(string from, string to, string cc, string subject, string body,bool isBodyHtml)
        {
            this.mail = new MailMessage();
            this.sentFrom = from;
            this.sendTo = to;
            this.sendCC = cc;
            this.subject = subject;
            this.body = body;
            this.mail.IsBodyHtml = isBodyHtml;
        }

        public void Attach(String fullFileName)
        {
            // if we get here, we have a file to attach
            Attachment attachment = new Attachment(fullFileName);
            this.mail.Attachments.Add(attachment);
        }

        /// <summary>
        /// Once you have set all the properties, then you can send you message using this method
        /// </summary>
        /// <returns>true if there were no errors</returns>
        public bool Send()
        {
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.From = new MailAddress(this.sentFrom);

            string[] receivers = sendTo.Split(';');
            foreach (string alias in receivers)
            {
                mail.To.Add(new MailAddress(alias));
            }

            if (!string.IsNullOrEmpty(this.sendCC))
            {
                receivers = sendCC.Split(';');
                foreach (string alias in receivers)
                {
                    mail.CC.Add(new MailAddress(alias));
                }
            }
            mail.Body = this.body;
            mail.Subject = this.subject;
            SmtpClient smtpClient = new SmtpClient(this.smtpServer);

            try
            {
                // Add credentials if the SMTP server requires them.
                smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                smtpClient.Send(this.mail);
                return true;
            }
            catch (Exception anyException)
            {
                return false;
            }
        }

        /// <summary>
        /// Allows you to specify a different server to send email from
        /// </summary>
        public String SmtpServer
        {
            get { return this.smtpServer; }
            set { this.smtpServer = value; }
        }
    }
}
